package com.jiuyin.dianjing.util;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import com.jiuyin.dianjing.BuildConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.jiuyin.dianjing.constant.HelperConstant.CRASH_DIR_NAME;
import static com.jiuyin.dianjing.constant.HelperConstant.FILE_PREFIX;
import static com.jiuyin.dianjing.constant.HelperConstant.PROGRAM_APP_ID;

/**
 * @author Administrator
 */
public class ExceptionUtil implements Thread.UncaughtExceptionHandler {
    private static final ThreadLocal<SimpleDateFormat> S_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("SimpleDateFormat")
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private ExceptionUtil() {

    }

    public static ExceptionUtil getInstance() {
        return InstanceHolder.handler;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if (BuildConfig.DEBUG) {
            if (!handleException(throwable) && null != mDefaultHandler) {
                mDefaultHandler.uncaughtException(thread, throwable);
            } else {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    private void saveFile(Throwable throwable) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        throwable.printStackTrace(printWriter);
        Throwable cause = throwable.getCause();
        while (null != cause) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String str = writer.toString();
        saveFile(str);
    }

    private void saveFile(String message) {
        String fileName = "crash_" + S_DATE_FORMAT.get().format(new Date()) + FILE_PREFIX;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + PROGRAM_APP_ID + File.separator + CRASH_DIR_NAME;
            boolean canWrite = Environment.getExternalStorageDirectory().canWrite();
            LogUtil.logOnly("ExceptionUtil saveFile canWrite = " + canWrite);
            File file = new File(storagePath, fileName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try (FileWriter fileWriter = new FileWriter(file, true)) {
                fileWriter.write(message);
            } catch (IOException e) {
            }
        }
    }

    private boolean handleException(Throwable throwable) {
        if (null == throwable) {
            return false;
        }
        new Thread(() -> {
            Looper.prepare();
            Toast.makeText(mContext, "program quit caused by exception ", Toast.LENGTH_SHORT).show();
            Looper.loop();
        }).start();
        saveFile(throwable);
        return true;
    }

    private static class InstanceHolder {
        static ExceptionUtil handler = new ExceptionUtil();
    }

}
